
package com.jz.action;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.jz.model.User;
import com.jz.util.CreateAuthNumberUtils;
import com.jz.util.Result;
import com.jz.util.StringUtils;



public class BaseAction extends com.opensymphony.xwork2.ActionSupport {
	protected Logger logger = Logger.getLogger(this.getClass());
	public static final String PURPOSE_GET_TOKEN = "_get_passport_token";
	private static final DateFormat TF;
	static {
		TimeZone.setDefault(TimeZone.getTimeZone("GMT+8:00"));
		TF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	}
	public static final String SESSION_AUTH_NUMBER_KEY = "_session_auth_number_key";
	
	protected User currentUser;
	protected User domainUser;
	protected Date currentTime;
	
	protected String forword;
	protected String from;
	protected String purpose;
	protected String spNumber;
	protected String secret;
	protected String parmetersString;

	private List actionErrors;
	private List actionMessages;
	
	private List pageErrors;
	private List pageMessages;
	protected String to;
	protected String id;
	protected Result result;
	protected int pageSize = 5;
	protected int page = 1;
	
	/**
	 * @return the page
	 */
	public int getPage() {
		return page;
	}

	/**
	 * @param page the page to set
	 */
	public void setPage(int page) {
		this.page = page;
	}

	/**
	 * @return the pageSize
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * @param pageSize the pageSize to set
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	/**
	 * @return the result
	 */
	public Result getResult() {
		return result;
	}

	/**
	 * @param result the result to set
	 */
	public void setResult(Result result) {
		this.result = result;
	}

	public String getParmetersString() throws UnsupportedEncodingException {
		if (parmetersString == null) {
			parmetersString = "";
			StringBuffer sb = new StringBuffer();
			boolean isFirst = true;
			if (StringUtils.isNotEmpty(forword)) {
					isFirst = false;
					sb.append("forword=").append(URLEncoder.encode(forword, "UTF-8"));
			}
			
			if (StringUtils.isNotEmpty(purpose)) {
				if (!isFirst)
					sb.append("&");
				else isFirst = false;
				sb.append("purpose=").append(URLEncoder.encode(purpose, "UTF-8"));
			}
			
			if (StringUtils.isNotEmpty(spNumber)) {
				if (!isFirst)
					sb.append("&");
				else isFirst = false;
				sb.append("spNumber=").append(URLEncoder.encode(spNumber, "UTF-8"));
			}
			
			if (StringUtils.isNotEmpty(secret)) {
				if (!isFirst)
					sb.append("&");
				else isFirst = false;
				sb.append("secret=").append(URLEncoder.encode(secret, "UTF-8"));
			}
		
			if (StringUtils.isNotEmpty(from)) {
				if (!isFirst)
					sb.append("&");
				else isFirst = false;
				sb.append("from=").append(URLEncoder.encode(from, "UTF-8"));
			}
			if (sb.length() > 1) 
				parmetersString = sb.toString();
		}
		return parmetersString;
	}
	
    public void saveMessage(String msg) {
        List messages = (List) getSession().getAttribute("messages");
        if (messages == null) {
            messages = new ArrayList();
        }
        messages.add(msg);
        getSession().setAttribute("messages", messages);
    }
    
	public void saveError(String error) {
		List errors = (List) getSession().getAttribute("errors");
		if (errors == null) {
			errors = new ArrayList();
		}
		errors.add(error);
		getSession().setAttribute("errors", errors);
	}
	
	public void saveErrors(Collection errors) {
		for (Iterator i = errors.iterator(); i.hasNext();) {
			saveError((String) i.next());
		}
	}
	public List getPageMessage() {
		if (pageMessages != null) {
			return pageMessages;
		}
		List list = (List) getSession().getAttribute("messages");
		if (list != null) {
			pageMessages = list;
			getSession().removeAttribute("messages");
		}
		return list;
	}
	
	public List getPageError() {
		if (pageErrors != null) {
			return pageErrors;
		} else {
			List list = (List) getSession().getAttribute("errors");
			if (list != null) {
				pageErrors = list;
				getSession().removeAttribute("errors");
			}
			return list;
		}
	}
	
	public void persistMessages() {
		if (hasActionMessages()) {
			for (Iterator i = getActionMessages().iterator(); i.hasNext();) {
				saveMessage((String) i.next());
			}
		}
		saveErrors(mergeActionErrors());
	}
	
	public List mergeActionErrors() {
		List errors = new ArrayList();
		if (hasActionErrors()) {
			for (Iterator i = getActionErrors().iterator(); i.hasNext();) {
				errors.add(i.next());
			}
		}
		if (hasFieldErrors()) {
			Map fieldErrors = getFieldErrors();
			for (Iterator i = fieldErrors.values().iterator(); i.hasNext();) {
				List errorList = (List) i.next();
				for (Iterator iter = errorList.iterator(); iter.hasNext();) {
					errors.add(iter.next());
				}
			}
		}
		return errors;
	}
	
	public void saveActionMessage(String message) {
		if (actionMessages == null) {
			actionMessages = new ArrayList();
		}
		actionMessages.add(message);
	}
	
	public void saveActionError(String error) {
		if (actionErrors == null) {
			actionErrors = new ArrayList();
		}
		actionErrors.add(error);
	}
    
    
    /**
	 * @return the actionErrors
	 */
	public List getActionErrors() {
		return actionErrors;
	}

	/**
	 * @return the actionMessages
	 */
	public List getActionMessages() {
		return actionMessages;
	}

	
	
	
	
	public Date getCurrentTime() {
		if (currentTime == null) {
			return new Date();
		}
		return currentTime;
	}
	
	

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	
	
	 public HttpServletResponse getResponse() {
	        return ServletActionContext.getResponse();
	    }
	
	public String redirect(String url) throws IOException {
    	getResponse().sendRedirect(getResponse().encodeRedirectURL(url));
    	return NONE;
    }
	
	public void drawAuthNumber(String []numbers) {
		BufferedImage image = CreateAuthNumberUtils.createNumberImage(numbers);
		 try {
			ImageIO.write(image, "JPEG", getResponse().getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
     * Convenience method to get the request
     * @return current request
     */
    public HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();  
    }
        
    /**
     * Convenience method to get the session
     */
    public HttpSession getSession() {
    	return getRequest().getSession();
    }
    
    /**
     * Convenience method to get the session
     */
    public HttpSession getSession(boolean create) {
    	return getRequest().getSession(create);
    }
    
   
    







	public void setDomainUser(User user) {
		this.domainUser = user;
	}

	public String getForword() {
		return forword;
	}

	public void setForword(String forword) {
		this.forword = forword;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getPurpose() {
		return purpose;
	}

	public void setPurpose(String purpose) {
		this.purpose = purpose;
	}

	public String getSecret() {
		return secret;
	}

	public void setSecret(String secret) {
		this.secret = secret;
	}

	public String getSpNumber() {
		return spNumber;
	}

	public void setSpNumber(String spNumber) {
		this.spNumber = spNumber;
	}
	
	
	
	public static String getRedirectParmetersUrl(Map<String, String> pars) {
		StringBuffer url = new StringBuffer();
		if (pars != null || pars.size() < 1) {
			url.append("?");
		}
		Iterator <Entry<String, String>> it = pars.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> en = it.next();
			try {
				url.append(en.getKey()).append("=").append(URLEncoder.encode(en.getValue(), "UTF-8"));
				if (it.hasNext()) {
					url.append("&");
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return url.toString();
	}
	
	public static String getRedirectParmeterUrl(String key, String par) {
		if (key != null && par != null) {
			try {
				return "?" + key + "=" + URLEncoder.encode(par, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * @return the to
	 */
	public String getTo() {
		return (String)this.getSession().getAttribute("url_to");
	}

	/**
	 * @param to the to to set
	 */
	public void setTo(String to) {
		this.to = to;
		this.getSession().setAttribute("url_to", to);
	}
	
	public void cleanToContent() {
		this.getSession().removeAttribute("url_to");
	}
	
	public long getLeftSeconds(String targetTime) {
		Date date = null;
		try {
			System.out.println(Locale.getDefault().toString());
			date = TF.parse("2010-11-09 15:00");
			System.out.println(date.getTime() +"?????"+ new Date().getTime());
		} catch (ParseException e) {
		}
		if (date == null) return 0;
		long leftSeconds = date.getTime() - System.currentTimeMillis();
		if (leftSeconds < 0) {
			leftSeconds = 0;
		} else {
			leftSeconds = leftSeconds / 1000;
		}
		return leftSeconds;
	}
	
	public int getYear() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.YEAR);
	}
	public int getMonth() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.MONTH);
	}
	public int getDate() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.DATE);
	}
	public int getHour() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.HOUR_OF_DAY);
	}
	public int getMinute() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.MINUTE);
	}
}
